<template>
  <div>
    <el-alert title="每天8点-17点可申请" type="error" v-show="disabled" show-icon style="margin-bottom: 10px"></el-alert>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="form.userName" @blur="nameBlur" placeholder="只能输入3个以内的汉字"></el-input>
      </el-form-item>
      <el-form-item label="原因" prop="reason">
        <el-input v-model="form.reason" placeholder="不少于10个字"></el-input>
      </el-form-item>
      <el-form-item label="菜谱">
        <el-select v-model="form.caipu" placeholder="请选择" style="width: 60%; float: left">
          <el-option v-for="item in caipus" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <span>仅郑州可用</span>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="form.workType" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in types" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="num" v-if="form.workType !== '工作日加班'">
        <el-input v-model.number="form.num" placeholder="不能大于2"></el-input>
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="form.bumen" filterable placeholder="请选择" style="width: 100%">
          <el-option v-for="item in deps" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" @click="onSubmit(form.workType === '工作日加班' ? 1:  form.num)" :loading="loading" :disabled="disabled">订餐</el-button>
      <el-button @click="onSubmit(0)" :loading="loading" :disabled="disabled">取消订餐</el-button>
    </el-form>
  </div>
</template>
<script type="text/javascript">
  import { mapGetters, mapMutations, mapActions } from 'vuex'
  import axios from 'axios'
  import qs from 'qs'

  export default {
    data () {
      return {
        form: {
          num: 2
        },
        loading: false,
        disabled: false,
        caipus: ['春光餐券', '老管家餐券', '亚新餐券'],
        types: ['工作日加班', '周末加班', '节假日加班'],
        deps: ['IT规划与信息安全部-信息安全',
          '云计算产品部-技术服务二处',
          '云计算产品部-技术服务处',
          '人力资源部-HRBP',
          '存储研发部-研发一处',
          '存储研发部-研发三处',
          '存储研发部-研发五处',
          '存储研发部-研发四处',
          '服务与实施部-人工智能与高性能产品服务交付处',
          '服务与实施部-呼叫中心处',
          '服务与实施部-存储和云产品服务交付处',
          '服务与实施部-数据中心服务交付处',
          '服务与实施部-服务器技术支持处',
          '服务与实施部-服务器服务交付处',
          '服务与实施部-服务指挥处',
          '服务与实施部-高端产品服务交付处',
          '测试验证部-一处',
          '测试验证部-七处',
          '测试验证部-三处',
          '测试验证部-二处',
          '测试验证部-四处',
          '测试验证部-测试三处',
          '测试验证部-测试四处',
          '研发与技术管理部-实验室管理',
          '研发与技术管理部-平台管理',
          '研发与技术管理部-科研管理',
          '系统软件部-研发一处',
          '系统软件部-研发三处',
          '系统软件部-研发二处',
          '系统软件部-研发五处',
          '系统软件部-研发六处',
          '系统软件部-研发四处',
          '系统软件部-项目管理',
          '综合管理部-行政-郑州',
          '综合管理部-部门助理',
          '财务部-无',
          '质量管理部-质量二处（职员）'],
        rules: {
          userName: [
            { required: true, pattern: /^[\u4e00-\u9fa5]{1,3}$/gi, message: '只能输入3个以内的汉字', trigger: 'change' }
          ],
          reason: [
            { required: true, min: 10, message: '不少于10个字', trigger: 'change' }
          ],
          num: [
            { type: 'number', required: true, min: 0, max: 2, message: '不能大于2', trigger: 'change' }
          ]
        }
      }
    },
    mounted () {
      this.$set(this.form, 'caipu', this.caipus[0])
      this.$set(this.form, 'bumen', this.deps[0])

      if (localStorage.__order) {
        this.$set(this, 'form', JSON.parse(localStorage.__order))
      }

      let now = new Date()
      if (now.getDay() === 0 || now.getDay() === 6) {
        this.$set(this.form, 'workType', this.types[1])
      } else {
        this.$set(this.form, 'workType', this.types[0])
      }
      this.disabled = !(now.getHours() > 8 && now.getHours() < 17)

      setInterval( _this => {
        let now = new Date()
        _this.disabled = !(now.getHours() > 8 && now.getHours() < 17)
      }, 60 * 1000, this)

      axios({
        methods: 'post',
        url: `${this.urlOrderBumen}?timestamp=${new Date().getTime()}`
      }).then(response => {
        this.employeeMap = response.data
        let deps = []
        let set = new Set()
        for (let e in this.employeeMap) {
          set.add(this.employeeMap[e])
        }
        set.forEach(x => deps.push(x))
        this.$set(this, 'deps', deps.sort())
      }).catch(error => {
        this.$message.error('连接订餐系统失败：' + error)
      })
    },
    computed:{
      ...mapGetters(['urlOrder', 'urlOrderBumen']),
    },
    methods: {
      nameBlur () {
        this.$set(this.form, 'bumen', this.employeeMap[this.form.userName])
      },
      onSubmit (num) {
        this.$refs.form.validate( valid => {
          if (valid) {
            this.loading = true
            //只有订餐时才保存
            if (num) {
              localStorage.__order = JSON.stringify(this.form)
            }

            let url = `${this.urlOrder}?timestamp=${new Date().getTime()}`
            
            let params = qs.stringify(Object.assign({ workDate: new Date().format('yyyy-MM-dd'), num }, this.form))
            
            axios({
              method: 'post',
              url,
              headers: {
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
              },
              data: params,
              params
            }).then(response => {
              this.$message({
                type: 'success',
                message: `${num ? '' : '取消'}订餐成功`
              })

              this.loading = false
            })
            .catch(error => {
              this.$message({
                type: 'error',
                message: `${num ? '' : '取消'}订餐失败`
              })
              console.log(`${num ? '' : '取消'}订餐失败: `, error)

              this.loading = false
            })
          }
        })
      }
    }
  }
</script>